// 对Sock进行封装
#pragma once
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <cstring>
#include <string>
#include <error.h>

#include "Err.hpp"
#include "Log.hpp"

static const int defaultnum = -1;
static const int gback = 32;
class Sock
{
public:
    Sock() : _listensock(defaultnum)
    {
    }

    ~Sock()
    {
        if (_listensock != defaultnum)
        {
            close(_listensock);
        }
    }

    // 1、创建套接字
    void Socket()
    {
        _listensock = socket(AF_INET, SOCK_STREAM, 0);
        if (_listensock < 0)
        {
            logMessage(FATAL, "socket fail");
            exit(SOCKET_ERR);
        }

        // 设置地址复用
        logMessage(NORMAL, "create socket success:%d", _listensock);
        int opt = 1;
        setsockopt(_listensock, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt));
    }

    // 2、绑定
    void Bind(uint16_t port)
    {
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(port);
        local.sin_addr.s_addr = INADDR_ANY;
        if (bind(_listensock, (struct sockaddr *)&local, sizeof(local)) < 0)
        {
            logMessage(FATAL, "bind fail");
            exit(BIND_ERR);
        }
        logMessage(NORMAL, "bind socket success");
    }

    // 3、设置监听状态
    void Listen()
    {
        if (listen(_listensock, gback) < 0)
        {
            logMessage(FATAL, "listen fail");
            exit(LISTEN_ERR);
        }

        logMessage(NORMAL, "listen socket success");
    }

    // 4、获取新连接
    int Accept(std::string *clientIP, uint16_t *clientPort, int *err)
    {
        struct sockaddr_in peer;
        memset(&peer, 0, sizeof(peer));
        socklen_t len = sizeof(peer);
        int sock = accept(_listensock, (struct sockaddr *)&peer, &len);
        *err = errno;
        if (sock < 0)
        {
            logMessage(FATAL, "accept fail");
            exit(ACCEPT_ERR);
        }
        logMessage(NORMAL, "accept socket success,a new sock :%d", sock);
        *clientIP = inet_ntoa(peer.sin_addr);
        *clientPort = ntohs(peer.sin_port);

        return sock;
    }

    int Fd()
    {
        return _listensock;
    }

    void Close()
    {
        close(_listensock);
    }

private:
    int _listensock;
};